package cn.lg.soar.database.query;

import lombok.Getter;
import lombok.Setter;

import java.util.Set;

/**
 * 字段信息
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Getter
public class FieldInfo {

    /**
     * 实体属性名
     */
    private final String property;

    /**
     * 数据库列名
     */
    private final String column;

    /**
     * 列名和属性名映射
     */
    private final String selectStr;

    /**
     * 字段java数据类型
     */
    private final Class<?> type;

    /**
     * 是否允许select列表查询该字段
     */
    @Setter
    private boolean selectAble;

    /**
     * 是否允许使用该字段排序
     */
    @Setter
    private boolean sortable;

    /**
     * 是否允许在 where 条件列表使用该字段
     */
    @Setter
    private boolean whereAble;

    /**
     * 条件名单类型
     * true：黑名单
     * false：白名单，默认
     */
    @Setter
    private boolean isBlacklist;

    /**
     * 条件名单
     */
    @Setter
    private Set<ConditionEnum> conditions;

    private FieldInfo(String property, String column, Class<?> type) {
        this.property = property;
        this.column = column;
        this.type = type;
        if (column.equals(property)) {
            this.selectStr = this.column;
        } else {
            this.selectStr = this.column + " AS `" + property + "`";
        }
    }

    public static FieldInfo create(String property, String column, Class<?> type) {
        FieldInfo fieldInfo = new FieldInfo(property, column, type);
        fieldInfo.whereAble = true;
        fieldInfo.selectAble = true;
        fieldInfo.sortable = true;
        return fieldInfo;
    }

    public static FieldInfo createInner(String property, String column, Class<?> type) {
        return new FieldInfo(property, column, type);
    }

    /**
     * 是否是允许的条件
     * @param condition
     * @return
     */
    public boolean allow(ConditionEnum condition) {
        if (conditions == null) {
            return true;
        }
        if (isBlacklist) {
            return !conditions.contains(condition);
        }
        return conditions.contains(condition);
    }
}
